package com.fjeld.swingx.table;

import com.fjeld.middleware.util.collection.ObservableArrayList;
import com.fjeld.middleware.util.collection.ObservableHashMap;
import org.apache.log4j.Logger;

import javax.swing.event.ListSelectionEvent;
import javax.swing.table.AbstractTableModel;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: fjeld
 * Date: 28/12/2011
 * Time: 01:55
 *
 * Observers an observable collections and fires an event when changed.
 */
public class ObserverTableModel extends AbstractTableModel implements Observer
{
    private static final Logger logger = Logger.getLogger(ObserverTableModel.class);

    protected List list = null;
    private String[] headers = null;

    public ObserverTableModel(String... headers)
    {
        this.headers = headers;
    }

    public void setData(ObservableArrayList list)
    {
        if (null != this.list)
        {
            throw new IllegalArgumentException("Already setup to use a list and observing the source.");
        }

        this.list = list;
        list.addObserver(this);
        fireTableDataChanged();
    }

    @Override
    public String getColumnName(int i)
    {
        if (null != headers && 0 != headers.length)
            return headers[i];

        return null;
    }

    public int getRowCount()
    {
        if (null != list)
            return list.size();

        return 0;
    }

    public int getColumnCount()
    {
        if (null == headers)
            return 0;
        return headers.length;
    }

    public Object getValueAt(int row, int col)
    {
        return "val at " + row + "x" + col;
    }

    public void update(Observable observable, Object o)
    {
        logger.info("Firing table data change! size: " + getRowCount());
        // Todo: ensure new and updated items are updated.
        fireTableDataChanged();
    }
}
